#pragma
#include<iostream>
#include<unistd.h>
#include<vector>
#include "Channel.hpp"
#include<functional>
#include <sys/types.h>
#include <sys/wait.h>
typedef std::function<void()> work_t;
class TaskManager{
public:
    int AddTask(work_t task){
        tasks.push_back(task);
        return tasks.size()-1;
    }
    std::vector<work_t> tasks;
};
class ProcessPool {
public:
    ProcessPool(int processCount,work_t work):_processCount(processCount),_work(work){
        for(int i=0;i<processCount;i++){
            
            //创建管道
            int pipefd[2];
            if(pipe(pipefd)<0){
                perror("pipe:");
                exit(1);
            }
            //创建子进程
            pid_t pid=fork();
            if(pid<0){
                perror("fork:");
                exit(1);
            }
            else if(pid==0){
                //子进程关闭写端
                ::close(pipefd[1]);
                dup2(pipefd[0],0);
                work();
                //如果这里不退出会打印多次
                exit(0);
            }
            else{
                //父进程关闭读端
                ::close(pipefd[0]);
                _channels.push_back(Channel(pipefd[1],pid));

            }
        }
    };
    void DispatchTask(){
        int num=0,cnt=0,taskid=0;
        std::cout<<"DispatchTask"<<std::endl;
        while(cnt<10){
            num=rand()%_processCount;
            taskid=rand()%4;
            _channels[num].Send(taskid);
            sleep(1);
            cnt++;
            //std::cout<<num<<std::endl;
        }
    }
    ~ProcessPool(){
        for(int i=_channels.size()-1;i>=0;i--){
            _channels[i].Close();
            int f=waitpid(_channels[i].Pid(),nullptr,0);
            if(f<0){
                perror("waitpid:");
            }
        }
    }
private:
    std::vector<Channel> _channels;
    int _processCount;
    work_t _work;
};
